//------------------------------------------------------------------------------
//  Library Javascript for check form validity
//  
//  @Author  : hthieu1110
//  @Email   : tronghieu.ha@gmail.com
//  @Version : 1.0   
//  
//  @Var JSON array @formFields formFields is the JSON array [{}, {}, {}]
//  @Var function onValid callback function when form is valid
//  @Var function onInvalid callback function when form is not valid
//  @Var function onProcess
//  @Var function onFinish
//
//  Template RegExp for check email
//  /^[-a-z0-9!#$%&'*+\/=?^_`{|}~]+(\.[-a-z0-9!#$%&'*+\/=?^_`{|}~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){2,63}$/i
//  
//  @Description:
//     Check form fields
//     Input format: array [{fieldId: 'fieldId1', fieldType: 'fieldType1', errorId: 'errorId1', errorMessage: 'errorMessage1', required: true/false ,maxLength: 'maxLength1'}, ...]
//     formFields is the JSON array [{}, {}, {}]
//     When use text type, you need to specify the maxLength
//     We have formFields to check and the 2 callback functions: onValidCallback, onInvalidCallback
//------------------------------------------------------------------------------

$.fn.checkForm = function(params) {
    $(this).submit(function(event){
        // Prevent default function
        event.preventDefault();
        
        // Call the onProcess
        // If the onProcess function is not defined then show the error
        if (!$.isFunction(params.onProcess)) {
            alert('Error: You have to define the onProcess callback function.');

        // Call the onProcess function
        } else {
        	params.onProcess();
        }
        
        var isFormValid = true;
        
        var formFields = params.formFields;
        for(var i = 0; i < formFields.length; i++) {
            var fieldId = formFields[i].fieldId;
            var fieldType = formFields[i].fieldType;
            var errorId = formFields[i].errorId;
            var errorMessage = formFields[i].errorMessage;
            var required = formFields[i].required;

            switch(fieldType) {
                case 'text':
                    var maxLength = formFields[i].maxLength;
                    $('#'+errorId).text('');

                    if (!$('#'+fieldId).isTextValid(maxLength, required)) {
                        $('#'+errorId).text(errorMessage);
                        isFormValid = false;
                    }
                    break;

                case 'telephone':
                    $('#'+errorId).text('');

                    if (!$('#'+fieldId).isTelephoneValid(required)) {
                        $('#'+errorId).text(errorMessage);
                        isFormValid = false;
                    }
                    break;

                case 'email':
                    $('#'+errorId).text('');

                    if (!$('#'+fieldId).isEmailValid(required)) {
                        $('#'+errorId).text(errorMessage);
                        isFormValid = false;
                    }
                    break;

                default:
                    alert('Field type is not valid');
                    isFormValid = false;
            }
        }

        // If form is not valid then call the onInvalid callback function
        if (!isFormValid) {
            // If the onInvalid callback function is not defined then show the error
            if (!$.isFunction(params.onInvalid)) {
                alert('Error: You have to define the onInvalid callback function.');

            // Call the onInvalid callback function
            } else {
            	params.onInvalid();
            }

        // If form is valid then call the onValid callback function
        } else {
            // If the onValid callback function is not defined then show the error
            if (!$.isFunction(params.onValid)) {
                alert('Error: You have to define the onValid callback function.');

            // Call the onValid callback function
            } else {
            	params.onValid();
            } 
        } 
        
        // Call the onFinish
        // If the onFinish function is not defined then show the error
        if (!$.isFunction(params.onFinish)) {
            alert('Error: You have to define the onFinish callback function.');

        // Call the onFinish function
        } else {
        	params.onFinish();
        }
    });
};

// Check email
$.fn.isEmailValid = function(required) {
    $(this).val($.trim($(this).val()).toLowerCase());
    var email = $(this).val();
    
    if (email == '' && required == false) return true;
    
    var emailRegexp = new RegExp("^[-a-z0-9!#$%&'*+\/=?^_`{|}~]+(\.[-a-z0-9!#$%&'*+\/=?^_`{|}~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){2,63}$",'i');
    
    return emailRegexp.test(email);
};

// Check text length
$.fn.isTextValid = function(maxLength, required) {
    $(this).val($.trim($(this).val()));
    var text = $(this).val();

    if (text == '' && required == false) return true;

    return (text.length <= maxLength);
};

// Check telephone
$.fn.isTelephoneValid = function(required) {
    $(this).val($.trim($(this).val().replace(/\s/g, '')));
    var telephone = $(this).val();
    
    if (telephone == '' && required == false) return true;
    
    var telephoneRegexp = new RegExp("^\\d{8,15}$");

    return telephoneRegexp.test(telephone);
};